<template>
  <van-cell-group inset>
    <div style="margin: 0 5%">
      <div className="my1" style="margin-top: 30%">
        <van-field label="账号" placeholder="请输入用户名" v-model="userAccount"/>
      </div>
      <div className="my1">
        <van-field label="密码" type="password" placeholder="请输入密码" v-model="userPassword"/>
      </div>
      <div className="my1 my2">
        <van-button type="primary" size="large" round @click="submit">
          登录
        </van-button>
      </div>
      <div className="my1 my2">
        <van-button type="primary" size="large" round @click="toRegister">
          注册
        </van-button>
      </div>

      <div className="my1">
        <van-loading
            color="#1989fa"
            vertical size="15%"
            v-show="isLoading"
        />
      </div>
    </div>
  </van-cell-group>
</template>

<script setup>
import {ref} from "vue";
import {currentUser} from "../config/globalConfig";
import {Toast} from "vant";
import {userLogin} from '../api/request'
import route from "../config/route";

const userAccount = ref('')
const userPassword = ref('')
const isLoading = ref(false)
// 登录请求
const submit = async () => {
  isLoading.value = true
  try {
    let result = await userLogin({
      userAccount: userAccount.value,
      userPassword: userPassword.value
    })
    result = result.data
    if (result.statusCode !== 0) {
      Toast(result.description)
    } else {
      Toast('登录成功')
      // 给对象相同的key赋值 好用
      Object.assign(currentUser, result.data)
      // 将登录信息存储到本地
      window.localStorage.setItem('currentUser',JSON.stringify(currentUser))
      await route.push('/user')
    }
  } catch (err) {
    console.log(err)
  }
  isLoading.value = false
}

// 注册跳转
const toRegister = () => {
  route.push('/register')
}

</script>

<style scoped>
.my1 {
  margin-top: 30px;
}

.my2 {
}
</style>